package service

import (
	"gitee.com/LangHuaHuachihua/cloud-gin-manager/models"
	"gitee.com/LangHuaHuachihua/cloud-gin-manager/serializer"
	"gitee.com/LangHuaHuachihua/cloud-gin-manager/utils"
	"github.com/gin-gonic/gin"
)

// UserLoginService 管理用户登录的服务
type UserLoginService struct {
	UserName string `form:"user_name" json:"user_name" binding:"required,min=5,max=30"`
	Password string `form:"password" json:"password" binding:"required,min=8,max=40"`
}

// Login 用户登录函数
func (service *UserLoginService) Login(c *gin.Context) serializer.Response {
	var user models.User

	if err := models.DB.Where("user_name = ?", service.UserName).First(&user).Error; err != nil {
		return serializer.ParamErr("账号或密码错误", nil)
	}

	if user.CheckPassword(service.Password) == false {
		return serializer.ParamErr("账号或密码错误", nil)
	}

	token, err := utils.SetToken(user.UserName, user.Model.ID)
	if err != nil {
		return serializer.TokenGetCheck()
	}

	return serializer.BuildLoginUserResponse(user, token, 1)
}
